<?php

namespace app\console\controller;



use think\Build;

use think\Db;

use think\Url;

use think\Cache;

use think\Loader;

use think\Session;

use think\Request;

use think\Exception;

use think\Controller;

use app\client\model\ShopSpecAttr;

use app\console\model\Brand as BrandModel;

use app\client\model\ShopGoods as ShopGoodsModel;

use app\console\model\GoodsType as GoodsTypeModel;

use app\common\trilateral\Classify as ClassifyAlias;

use app\client\model\ShopGoodsSpec as ShopGoodsSpecModel;

use app\client\model\ShopGoodsAttr as ShopGoodsAttrModel;

use app\client\model\ShopGoodsType as ShopGoodsTypeModel;

use app\client\model\ShopGoodsFlag as ShopGoodsFlagModel;



class ShopGoods extends Controller

{

	
	//岗位提成
	public function gangwei_ticheng()
	{
        $param = Request::instance()->param();
		if($param['type']=='index'){
		$goods_id = Request::instance()->param('id');
			$data = Db::name('job')
			->where('status', 1)
			->select()
			->toArray();
		if(!empty($data)){
				foreach ($data as &$v){
					$v['post_fuwu'] = Db::name('goods_gangwei')->where(['goods_id' => $goods_id])->where(['post_id' => $v['id']])->value('post_fuwu');
					$v['post_xiaoshou'] = Db::name('goods_gangwei')->where(['goods_id' => $goods_id])->where(['post_id' => $v['id']])->value('post_xiaoshou');
					
					$v['shop_title'] = Db::name('shop')->where(['id' => $v['shop_id']])->value('shop_title');
					if($v['post_fuwu']==''){
						$v['post_fuwu']='0';
					}
					
					if($v['post_xiaoshou']==''){
						$v['post_xiaoshou']='0';
					}
					
				}
        	 }
		 return view('', ['data' => $data,'goods_id'=>$goods_id]);	 
		}elseif($param['type']=='all'){
			$goods_id = Request::instance()->param('goods_id');
			$param1 = Request::instance()->param()['input1'];
			$param2 = Request::instance()->param()['input2'];
			/*************************************************/
			if (!empty($param1)) {
				$ret = false;
				foreach ($param1 as $k => $v) {
	
					$find = Db::name('goods_gangwei')->where(['post_id' => $k])->where(['goods_id' => $goods_id])->find();
					if($find){ //存在就是修改
						$ret = Db::name('goods_gangwei')->where(['post_id' => $k])->where(['goods_id' => $goods_id])->update(['post_fuwu' => $v,'post_xiaoshou' => $param2[$k]]);
					}else{
						$ret = Db::name('goods_gangwei')->insert([
							'goods_id' => $goods_id,
							'post_id' => $k,
							'post_fuwu' => $v,
							'post_xiaoshou' => $param2[$k]
						]);
					}
				}
				if ($ret !== false) {
				   wingo('操作成功', Url::build('ShopGoods/gangwei_ticheng',['id' => $goods_id]));
				}
        	}
		/*************************************************/	
		}
		
		
		
		
       /* $goods_id = Request::instance()->param('id');
		$data = Db::name('goods_gangwei g')
		->join('job j', 'g.post_id = j.id')
		->join('shop s', 's.id = j.shop_id')
		->field(['j.title', 'g.*','s.shop_title'])
		->where(['g.goods_id' => $goods_id,])
		->where(['g.is_delete' => '1',])
		->select();*/
       
    }
	
	
	public function gangwei_ticheng_zsg()
	{
        $param = Request::instance()->param();
        
		$type = Request::instance()->param('type');
		if($type=='add'){
			$goods_id = Request::instance()->param('goods_id');
			$data = Db::name('job j')
			->join('shop s', 's.id = j.shop_id')
			->field(['j.*','s.shop_title'])
			->where(['j.status' => '1',])
			->select();
			return view('gangwei_ticheng_add', ['data' => $data,'goods_id'=>$goods_id]);
		}elseif($type=='add_add'){
			$goods_id = Request::instance()->param('goods_id');
			$post_fuwu = Request::instance()->param('post_fuwu');
			$post_xiaoshou = Request::instance()->param('post_xiaoshou');
			$post_id = Request::instance()->param('post_id');
			$have = Db::name('goods_gangwei')->where(['post_id' => $post_id,])->where(['goods_id' => $goods_id,])->count();
			if($have >'0'){
				wingo('添加失败,该提成已存在', Url::build('ShopGoods/gangwei_ticheng',['id' => $goods_id]));
			}else{
				$order_add = Db::name('goods_gangwei')->insert(['goods_id' => $goods_id,'post_id' => $post_id,'post_fuwu' => $post_fuwu,'post_xiaoshou' => $post_xiaoshou]);
				wingo('操作成功', Url::build('ShopGoods/gangwei_ticheng',['id' => $goods_id]));
			}	
		}elseif($type=='del'){
			$id = Request::instance()->param('id');
			$goods_id = Request::instance()->param('goods_id');
			$finance_pay_cart = Db::name('goods_gangwei')->where(['id' => $id,])->delete();
			wingo('删除成功', Url::build('ShopGoods/gangwei_ticheng',['id' => $goods_id]));
			
		}elseif($type=='edit'){
			$goods_id = Request::instance()->param('goods_id');
			$id = Request::instance()->param('id');
			$post_fuwu = Db::name('goods_gangwei')->where(['id' => $id,])->value('post_fuwu');
			$post_xiaoshou = Db::name('goods_gangwei')->where(['id' => $id,])->value('post_xiaoshou');
			$post_id = Db::name('goods_gangwei')->where(['id' => $id,])->value('post_id');
			$title = Db::name('job')->where(['id' => $post_id,])->value('title');
			return view('gangwei_ticheng_edit', ['goods_id'=>$goods_id,'id'=>$id,'post_fuwu'=>$post_fuwu,'post_xiaoshou'=>$post_xiaoshou,'title'=>$title]);
		}elseif($type=='edit_edit'){
			$goods_id = Request::instance()->param('goods_id');
			$post_fuwu = Request::instance()->param('post_fuwu');
			$post_xiaoshou = Request::instance()->param('post_xiaoshou');
			$id = Request::instance()->param('id');
			$order_add = Db::name('goods_gangwei')->where('id', $id)->update(['post_xiaoshou' => $post_xiaoshou,'post_fuwu' => $post_fuwu]);
			wingo('修改成功', Url::build('ShopGoods/gangwei_ticheng',['id' => $goods_id]));	
		}
		
    }
	
	











    /*

     * 店铺分类选择

     */

    public function classify()

    {

        // 读取分类店铺商品

        $data = GoodsTypeModel::where(['count' => '1'])->field('id,title,count')->order(['id' => 'asc'])->where('auding_status',2)->where('is_delete',1)->select();





        return $this->fetch('classify', [

            "mate_title" => '商品分类选择',

            'data'       => $data,

        ]);



    }







    /*

     * 店铺商品列表

     */

    public function index($pa = 10)

    {

        // 获取参数

        $inquire = Request::instance()->param();



        // halt($inquire['orderId']);



        // 搜索条件

        $condition = [];

        $sort = ['sort' => 'asc', 'id' => 'desc'];

        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];

        //if (!empty($inquire['shop_class_id'])) $condition['parenTid'] = ['eq', $inquire['shop_class_id']];

        if (!empty($inquire['promotion'])) $condition['promotion'] = ['eq', $inquire['promotion']];

        //if (!empty($inquire['status'])) $condition['status'] = ['eq', $inquire['status']];

         if (!empty($inquire['state'])) $condition['state'] = ['eq', $inquire['state']];





        if (!empty($inquire['shop_class_id'])) $condition['goods_str'] = ['like','%,'.$inquire['shop_class_id'].',%'];



        // 读取店铺分类店铺商品

        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select();

        // 读取店铺商品

        $data = ShopGoodsModel::where($condition)->field('goods_sale,auding_status1,auding_status2,auding_status3,per,dc,code,auding_time,auding_id,auding_status,id,price,parenTid,sort,sale_number,title,update_time,create_id,create_time,recommend,related,promotion,status,state,inventory_hint,charges,inventory,shop_recommend,goods_id,auding_status')->order($sort)->paginate($pa, false, ['query' => $inquire])->each(function($item,$key){

            $item->mmff =  "(空)";

            $item->mmsm =  "(空)";

            $mmff = Db::name('goods_shop_price')->where('goods_id',$item->id)->column('price');



            if(!empty($mmff)){

               foreach ($mmff as $v1){

                   if(!empty($v1) && $v1 != '0.00'){

                       $item->mmff =  "";

                   }

               }

            }



            $mmsm = Db::name('goods_shop_price1')->where('goods_id',$item->id)->column('price');



            if(!empty($mmsm)){

                foreach ($mmsm as $v2){

                    if(!empty($v2) && $v2 != '0.00'){



                        $item->mmsm =  "";

                    }

                }

            }

        });

        if(isset($inquire['export'])){

            $this->push($data);

        }



        return $this->fetch('index', [

            'mate_title'   => '出售中的商品',

            'data'         => $data,

            'classify'     => ClassifyAlias::dimension(Cache::get('goodsType')),

            'shopClassify' => $shopClassify,



        ]);

    }



    /**

     * 商品对应每个业务员

     */

    public function salesman()

    {

        $where = [];

        $salesman_id = Request::instance()->param('salesman_id',0);

        $list = Salesman::salesman_public(input('id'),input('type'),$salesman_id);

        $data = Db::name('salesman s')

            ->join('manager m', 's.manage_id = m.id', 'left')

            ->field('m.username,m.nickname,m.create_time,s.*,m.id,m.telephone')

            ->where('m.level', 4)

            ->select()->toArray();

        $data = getMenuTree1($data,0);

        return view('', ['list' => $list,'sl' => $data]);

    }



    public function salesman_update()

    {

        try {

            $type_pk_id = input('id');

            $param = Request::instance()->param()['input'];

            $type = input('type');

            $cod = input('code');

            $code = [1 => '商品',3 => '礼包',2 => '服务'];

            //$param2 = Request::instance()->param()['input2'];

            if (!empty($param)) {

                $ret = false;

                foreach ($param as $k => $v) {

                    $find = Db::name('salesman_price')->where('salesman_id', $k)->where('type', $type)->where('type_pk_id', $type_pk_id)->find();

                    if ($find) { //存在就是修改

                        $ret = Db::name('salesman_price')->where('salesman_id', $k)->where('type', $type)->where('type_pk_id', $type_pk_id)->update(['per' => $v]);

                    } else {

                        $ret = Db::name('salesman_price')->insert([

                            'salesman_id' => $k,

                            'type' => $type,

                            'type_pk_id' => $type_pk_id,

                            'per' => $v, //$param[$k] = $v

                            //'person_price' => $param2[$k],

                            'create_time' => date('Y-m-d H:i:s', time())

                        ]);

                    }

                }

                if ($ret !== false) {

                    win($code[$type] . '分销比设置完毕', Url::build('salesman', ['id' => $type_pk_id, 'type' => $type,'code' => $cod]));

                }

            }

        } catch (Exception $e) {

            return json(['code' => $e->getCode(), 'message' => $e->getMessage(), 'line' => $e->getLine()]);

        }

    }



    public function push($data,$name = '库存商品导出')

    {



        set_time_limit(0);

        ini_set('memory_limit', '1024M');

        error_reporting(E_ALL);

        date_default_timezone_set('Asia/Shanghai');



        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');

        $objPHPExcel = new \PHPExcel();



        /*以下是一些设置 ，什么作者  标题啊之类的*/

        $objPHPExcel->getProperties()->setCreator("管理员")

            ->setLastModifiedBy("管理员")

            ->setTitle("电话本导出")

            ->setSubject("数据EXCEL导出")

            ->setDescription("备份数据")

            ->setKeywords("excel")

            ->setCategory("result file");

        $objPHPExcel->setActiveSheetIndex(0)

            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

            ->setCellValue('A1', '科目代码')

            ->setCellValue('B1', '借贷方(绿色借方-灰色贷方)')

            ->setCellValue('C1', '商品ID')

            ->setCellValue('D1', '所属分类')

            ->setCellValue('E1', '商品名称')

            ->setCellValue('F1', '价钱')

            ->setCellValue('G1', '总库存')

            ->setCellValue('H1', '总销量')

            ->setCellValue('I1', '创建时间')

        ;

        $sheet1 = ['A', 'B', 'C', 'D', 'E'];



        for ($x = 0; $x < count($sheet1); $x++) {

            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(

                array(

                    'font'      => array(

                        'bold' => true

                    ),

                    'alignment' => array(

                        'horizontal' =>

                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER

                    )

                )

            );

        }



        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/



        $n = 0;

        foreach ($data as $v) {



            $num = $n + 2;

            $objPHPExcel->setActiveSheetIndex(0)

                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

                ->setCellValue('A' . $num, "\t".$v['code']."\t")

                ->setCellValue('B' . $num, $v['dc_text'])

                ->setCellValue('C' . $num, "\t".$v['id']."\t")

                ->setCellValue('D' . $num, $v['goods_type'])

                ->setCellValue('E' . $num, $v['title'])

                ->setCellValue('F' . $num, $v['price'])

                ->setCellValue('G' . $num, $v['inventory_sum'])

                ->setCellValue('H' . $num, $v['sale_number'])

                ->setCellValue('I' . $num, $v['create_time'])



            ;

            $n++;

        }



        $objPHPExcel->getActiveSheet(0)->setTitle('库存商品导出');

        $objPHPExcel->setActiveSheetIndex(0);



        ob_end_clean();

        header('Content-Type: application/vnd.ms-excel');

        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');

        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $objWriter->save('php://output');

        exit;

    }



    /**

     * 栏目状态改变

     */

    public function dc($id, Request $request, ShopGoodsModel $model)

    {

        $id = $request->instance()->param('id');



        $status = $model->where('id', $id)->value('dc') == '1' ? 2 : 1;



        if ($model->where('id', $id)->update(['dc' => $status])) {

            return $status;

        }

        return false;

    }



    public function code(){

        $param = Request::instance()->param()['code'];



        if(!empty($param)){



            foreach ($param as $k => $v){



                $ret = Db::name('shop_goods')->where('id',$k)->setField('code',$v);

            }

            if($ret !== false){

                win('科目代码设置成功',Url::build('index'));

            }

        }



    }



    /**

     * @return array|mixed|\think\response\View

     * 出库list

     */

    public function chuku()

    {

        $inquire = Request::instance()->param();



        // halt($inquire['orderId']);

        $condition=[];

        // 搜索条件

        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];

        if (!empty($inquire['shop_class_id'])) $condition['goods_str'] = ['like','%,'.$inquire['shop_class_id'].',%'];

        $param = Request::instance()->param();

        $cbj = 0 ;

        $zj = 0 ;



        $data = (new \app\console\model\ShopGoods())->order('id','desc')->where($condition)->paginate(20, false, ['query' => $param])->each(function ($item, $key) use(&$cbj,&$zj){

            $attr = Db::name('shop_spec_attr')->where('goods_id', $item->id)->where('shop_id',0)->select();

           $list = Db::name('shop_spec_attr')->where('goods_id', $item->id)->where('shop_id',0)->group('attribute')->select()->toArray();

           foreach ($list as $k => &$v){

               $str = '';

               $cbj += $v['bit'];

               $zj += $v['inventory']*$v['bit'];

               $records = Db::name('shop_spec_attr_auding_status')

                   ->alias('s')

                   ->join('manager m','s.auding_id = m.id','left')

                   ->where(['spec_id' => $v['id'],'type' => 1])

                   ->column('auding_text');

               $records2 = Db::name('shop_spec_attr_auding_status')

                   ->alias('s')

                   ->join('manager m','s.auding_id = m.id','left')

                   ->where(['spec_id' => $v['id'],'type' => 2])

                   ->column('auding_text');

               $v['level'] = implode(',',$records);

               $v['level2'] = implode(',',$records2);

           }

            $item->list =$list;

            $item->count = count(Db::name('shop_spec_attr')->where('goods_id', $item->id)->where('shop_id',0)->group('attribute')->select());

        });



        $data_cbj = (new \app\console\model\ShopGoods())->alias('sg')->where($condition)->join('shop_spec_attr ssa','ssa.goods_id = sg.id')->sum('bit');

        $data_zj = (new \app\console\model\ShopGoods())->alias('sg')->where($condition)->join('shop_spec_attr ssa','ssa.goods_id = sg.id')->field('sum(bit*ssa.inventory) zj')->find();

        if(isset($inquire['export'])){

            $this->push_chuku($data);

        }

        //dump($data->toArray());

        return view('', ['data' => $data,'cbj' => $data_cbj,'zj' => $data_zj['zj'],'classify'     => ClassifyAlias::dimension(Cache::get('goodsType'))]);

    }



    public function chuku_daochu()

    {

        $inquire = Request::instance()->param();



        // halt($inquire['orderId']);

        $condition=[];

        // 搜索条件

        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];

        if (!empty($inquire['shop_class_id'])) $condition['goods_str'] = ['like','%,'.$inquire['shop_class_id'].',%'];

        $param = Request::instance()->param();

        $data = (new \app\console\model\ShopGoods())

            ->alias('sg')

            ->join('shop_spec_attr ssa','ssa.goods_id = sg.id')

            ->where('ssa.shop_id',0)

            ->order('sg.id','desc')

            ->where($condition)

            ->select();

        if(isset($inquire['export'])){

            $this->push_chuku($data);

        }



        return view('', ['data' => $data,'classify'     => ClassifyAlias::dimension(Cache::get('goodsType'))]);

    }



    public function push_chuku($data,$name = '总库库存导出')

    {

        set_time_limit(0);

        ini_set('memory_limit', '1024M');

        error_reporting(E_ALL);

        date_default_timezone_set('Asia/Shanghai');



        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');

        $objPHPExcel = new \PHPExcel();



        /*以下是一些设置 ，什么作者  标题啊之类的*/

        $objPHPExcel->getProperties()->setCreator("管理员")

            ->setLastModifiedBy("管理员")

            ->setTitle("电话本导出")

            ->setSubject("数据EXCEL导出")

            ->setDescription("备份数据")

            ->setKeywords("excel")

            ->setCategory("result file");

        $objPHPExcel->setActiveSheetIndex(0)

            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

            ->setCellValue('A1', 'ID')

            ->setCellValue('B1', '商品名称')

            ->setCellValue('C1', '属性值')

            ->setCellValue('D1', '属性库存')

            ->setCellValue('E1', '成本价')

            ->setCellValue('F1', '总价')

        ;

        $sheet1 = ['A', 'B', 'C', 'D', 'E','F'];



        for ($x = 0; $x < count($sheet1); $x++) {

            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(

                array(

                    'font'      => array(

                        'bold' => true

                    ),

                    'alignment' => array(

                        'horizontal' =>

                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER

                    )

                )

            );

        }



        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/



        $n = 0;

        foreach ($data as $v) {



            $num = $n + 2;

            $objPHPExcel->setActiveSheetIndex(0)

                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

                ->setCellValue('A' . $num, $v['id'])

                ->setCellValue('B' . $num, $v['title'])

                ->setCellValue('C' . $num,$v['attribute'])

                ->setCellValue('D' . $num, $v['inventory'])

                ->setCellValue('E' . $num, $v['bit'])

                ->setCellValue('F' . $num, $v['inventory']*$v['bit'])

            ;

            $n++;

        }



        $objPHPExcel->getActiveSheet(0)->setTitle('总库库存导出');

        $objPHPExcel->setActiveSheetIndex(0);



        ob_end_clean();

        header('Content-Type: application/vnd.ms-excel');

        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');

        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $objWriter->save('php://output');

        exit;

    }







    /**

     * @param $id

     * @return array|mixed|\think\response\View

     * 总库存出库到门店

     */

    public function chuku_shop($id)

    {

        $param = Request::instance()->param();

        if (Request::instance()->isPost()) {



            $param['attribute'] =  Db::name('shop_spec_attr')->where('id', $param['id'])->value('attribute');

            if ($param['shop_id'] <= 0) {

                fail('必须选择门店');

            }

            if ($param['count'] <= 0) {

                fail('出库数量必须大于0');

            }

            $count = count($param['shop_id']) * $param['count'];

            if ($count > $param['inventory']) {

                fail('出库数量不能大于总库存');

            }

            $role_id = session('role_id');



            if($role_id == 2){

                $role_id = 11;  //如果是超级管理员或者管理员就当一级审核原来玩



            }

            $auding_text = '等待审核';

            if($role_id == 11){

                $auding_text = '一级审核';

            }

            if($role_id == 12){

                $auding_text = '二级审核';

            }

            if($role_id == 13){

                $auding_text = '三级审核';

            }

            $manage_id = session('manage_id');

            if (isset($param['auding_status'])) { //有审核状态 审核权限人 2是审核成功

                //多次审核

                if($role_id != 1) {

                    $ssaas_find = Db::name('shop_spec_attr_auding_status')->where('type', 2)->where('spec_id', $param['id'])->where('role_id', 3)->find();

                    if (empty($ssaas_find)) {

                        fail('没有录入员提交,无法审核');

                    }

                }

                if($role_id == 12){

                    $auding_status1 = Db::name('shop_spec_attr_auding_status')->where('type',2)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    if(empty($auding_status1)){

                        fail('请等一级审核完毕');

                    }

                }

                if($role_id == 13){

                    $auding_status1 = Db::name('shop_spec_attr_auding_status')->where('type',2)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    $auding_status2 = Db::name('shop_spec_attr_auding_status')->where('type',2)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    if(empty($auding_status1) || empty($auding_status2)){

                        fail('请等一二级审核完毕');

                    }

                }

                //超级管理员1 管理员2 一级审核员11 二级审核员12 三级审核员13

                $status = false;



                if($param['auding_status'] != 2){ //不是成功就是删除 重新来

                    Db::name('shop_spec_attr_auding_status')->where('spec_id',$param['id'])->delete(); //全部删除重新审核

                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',$param['reason']);

                    fail('您不同意审核,审核重新开始');

                }else{

                    //成功

                    $find = Db::name('shop_spec_attr_auding_status')->where([

                        'type' => 2,

                        'spec_id' => $param['id'],

                        'auding_status' => $param['auding_status'],

                        'role_id' => $role_id

                    ])->find(); //当前会员



                    if(!empty($find)) fail('本级别已经审核过');

                    $select = Db::name('shop_spec_attr_auding_status')->where([

                        'type' => 2,

                        'spec_id' => $param['id'],

                    ])->select(); //统计数量

                    if($role_id == 1){

                        $select = ['1','2',3];

                    }

                    if(count($select) == 3){ //如果已经有2条同意了 那就是正常添加了

                        Db::name('shop_spec_attr_auding_status')->where([

                            'type' => 2,

                            'spec_id' => $param['id'],

                        ])->delete(); //删除统计记录



                        foreach ($param['shop_id'] as $k => $v) {

                            $goods_attr = Db::name('shop_spec_attr')->where('goods_id', $param['goods_id'])->where('shop_id', $v)->where('attribute', $param['attribute'])->find();

                            if ($goods_attr) {

                                Db::name('shop_spec_attr')->where('goods_id', $param['goods_id'])->where('shop_id', $v)->where('attribute', $param['attribute'])->setInc('inventory', $param['count']);



                            } else {

                                Db::name('shop_spec_attr')->insert([

                                    'goods_id' => $param['goods_id'],

                                    'shop_id' => $v,

                                    'attribute' => $param['attribute'],

                                    'inventory' => $param['count']

                                ]);



                            }

                            $this->insert_records(2, $param['count'], $id, $v);

                            $ret123 = Db::name('shop_spec_attr')->where('goods_id', $param['goods_id'])->where('shop_id', 0)->where('inventory','gt',0)->where('attribute', $param['attribute'])->setDec('inventory', $param['count']);





                        }

                        wingo('出库成功', Url::build('chuku'));

                    }

                    Db::name('shop_spec_attr_auding_status')->insert([

                        'auding_text' => $auding_text,

                        'shop_str' => implode(',',$param['shop_id']),

                        'count' => $param['count'],

                        'bit' => 0,

                        'type' => 2,

                        'spec_id' => $param['id'],

                        'auding_status' => $param['auding_status'],

                        'auding_id' => $manage_id,

                        'role_id' => $role_id,

                        'create_time' => date('Y-m-d H:i:s',time())



                    ]);





                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',''); //成功 就没有失败原因 清空

                    wingo('审核完毕',Url::build('chuku'));

                }



            }else{

                $find = Db::name('shop_spec_attr_auding_status')->where([

                    'type' => 2,

                    'spec_id' => $param['id'],

                    'auding_status' => 2,

                    'role_id' => $role_id

                ])->find(); //当前会员



                if(!empty($find)) fail('本级别已经审核过');

                Db::name('shop_spec_attr_auding_status')->insert([

                    'auding_text' => '等待审核',

                    'shop_str' => implode(',',$param['shop_id']),

                    'count' => $param['count'],

                    'bit' => 0,

                    'type' => 2,

                    'spec_id' => $param['id'],

                    'auding_status' => 2,

                    'auding_id' => $manage_id,

                    'role_id' => $role_id,

                    'create_time' => date('Y-m-d H:i:s',time())



                ]);

                wingo('录入完毕',Url::build('chuku'));

            }



        }



        $shop_list = Db::name('shop')->where('is_delete', 1)->where('auding_status', 2)->select();

        $shenhe = Db::name('shop_spec_attr_auding_status')

            ->alias('s')

            ->field('m.*,s.*')

            ->join('manager m','s.auding_id = m.id')

            ->where(['spec_id' => $param['id'],'type' => 2])

            ->find();

        $records = Db::name('shop_spec_attr_auding_status')

            ->alias('s')

            ->field('m.*,s.*')

            ->join('manager m','s.auding_id = m.id','left')

            ->where(['spec_id' => $param['id'],'type' => 2])

            ->select()->toArray();

        foreach ($records as $k => &$v){

            $v['level'] = '等待审核';

            if($v['role_id'] == 11){

                $v['level'] = '一级审核';

            }

            if($v['role_id'] == 12){

                $v['level'] = '二级审核';

            }

            if($v['role_id'] == 13){

                $v['level'] = '三级审核';

            }

        }



        return view('', ['shop_list' => $shop_list,'item' => $shenhe,'records' => $records]);

    }









    public function ruku($id){

        $param = Request::instance()->param();



        if(Request::instance()->isPost()){

            if($param['count'] <= 0){

                fail('添加数量不能为0');

            }

            $role_id = session('role_id');



            if($role_id == 2){

                $role_id = 11;  //如果是超级管理员或者管理员就当一级审核原来玩



            }

            $auding_text = '等待审核';

            if($role_id == 11){

                $auding_text = '一级审核';

            }

            if($role_id == 12){

                $auding_text = '二级审核';

            }

            if($role_id == 13){

                $auding_text = '三级审核';

            }

            $manage_id = session('manage_id');

            if (isset($param['auding_status'])) { //有审核状态 审核权限人 2是审核成功

                //多次审核

                if($role_id != 1){

                    $ssaas_find = Db::name('shop_spec_attr_auding_status')->where('type',1)->where('spec_id',$param['id'])->where('role_id',3)->find();

                    if(empty($ssaas_find)){

                        fail('没有录入员提交,无法审核');

                    }

                }

                if($role_id == 12){

                    $auding_status1 = Db::name('shop_spec_attr_auding_status')->where('type',1)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    if(empty($auding_status1)){

                        fail('请等一级审核完毕');

                    }

                }

                if($role_id == 13){

                    $auding_status1 = Db::name('shop_spec_attr_auding_status')->where('type',1)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    $auding_status2 = Db::name('shop_spec_attr_auding_status')->where('type',1)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    if(empty($auding_status1) || empty($auding_status2)){

                        fail('请等一二级审核完毕');

                    }

                }



                //超级管理员1 管理员2 一级审核员11 二级审核员12 三级审核员13

                $status = false;



                if($param['auding_status'] != 2){ //不是成功就是删除 重新来

                    Db::name('shop_spec_attr_auding_status')->where('spec_id',$param['id'])->delete(); //全部删除重新审核

                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',$param['reason']);

                    fail('您不同意审核,审核重新开始');

                }else{ //=2

                    //成功

                    $find = Db::name('shop_spec_attr_auding_status')->where([

                        'type' => 1,

                        'spec_id' => $param['id'],

                        'auding_status' => $param['auding_status'],

                        'role_id' => $role_id

                    ])->find(); //当前会员



                    if(!empty($find)) fail('本级别已经审核过');

                    $select = Db::name('shop_spec_attr_auding_status')->where([

                        'type' => 1,

                        'spec_id' => $param['id'],

                    ])->select(); //统计数量

                    if($role_id == 1){

                        $select = ['1','2',3];

                    }

                    if(count($select) == 3){ //如果已经有2条同意了 那就是正常添加了

                        Db::name('shop_spec_attr_auding_status')->where([

                            'type' => 1,

                            'spec_id' => $param['id'],

                        ])->delete(); //删除统计记录

                        Db::name('shop_spec_attr_bit')->insert([

                            'spec_attr_id' => $param['id'],

                            'goods_id' => $param['goods_id'],

                            'bit' => $param['bit'],

                            'count' => $param['count'],

                            'total_bit' => $param['bit']*$param['count'],

                            'attribute' => $param['attribute'],

                            'inventory' => $param['inventory'],

                            'after_inventory' => $param['inventory']+$param['count'],

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        $goods_attr = Db::name('shop_spec_attr')->where('id',$id)->setInc('inventory',$param['count']);

                        Db::name('shop_spec_attr')->where('id',$id)->update(['count' =>$param['count'],'bit' => $param['bit'],'total_bit' => $param['count']*$param['bit']]);

                        if($goods_attr){

                            $this->insert_records(1,$param['count'],$id);

                            wingo('入库成功',Url::build('chuku'));

                        }

                    }

                    Db::name('shop_spec_attr_auding_status')->insert([

                        'auding_text' => $auding_text,

                        'count' => $param['count'],

                        'bit' => $param['bit'],

                        'type' => 1,

                        'spec_id' => $param['id'],

                        'auding_status' => $param['auding_status'],

                        'auding_id' => $manage_id,

                        'role_id' => $role_id,

                        'create_time' => date('Y-m-d H:i:s',time())



                        ]);





                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',''); //成功 就没有失败原因 清空

                    wingo('审核完毕',Url::build('chuku'));

                }

//                if($role_id == 1 || $role_id == 2 || $role_id == 11){

//                    Db::name('shop_spec_attr_auding_status')->insert();

//                    if($auding_status1 == 2 && $auding_status2 == 2 && $auding_status3 ==2){ //这有这一种情况是审核通过 其他全部是失败

//                        $status = true;

//                    }

//

//                }

//                if($role_id == 12){ //2级审核

//                    if($auding_status1 == 2 && $auding_status1 == 2 && $auding_status3 ==2){ //这有这一种情况是审核通过 其他全部是失败

//                        $status = true;

//                    }

//                }

//                if($role_id == 13){

//                    if($auding_status1 == 2 && $auding_status1 == 2 && $auding_status2 ==2){ //这有这一种情况是审核通过 其他全部是失败

//

//                        $status = true;

//                    }

//                }

//                if($status == true){

//                    $data->auding_status = 2;

//                    Db::name('member_coupon')->where('coupon_id',$data->id)->setField('auding_status',2);

//                    foreach (explode(',',Db::name('coupon')->where('id',$data->id)->value('shop_assignor_id')) as $k => $v){

//                        (new \app\index\controller\MemberMessage())->jpushMessage($v,'恭喜您获得优惠券'.Db::name('coupon')->where('id',$data->id)->value('number').'张',Db::name('coupon')->where('id',$data->id)->value('title'),3);

//

//                    }

//

//                }else{

//                    // $data->auding_status = $data->auding_status;使用默认提交值

//                    $data->auding_status = 3; //必须失败 否则 默认提交过来的auding_status 自动还是变成 1 2 3 状态;

//                    Db::name('member_coupon')->where('coupon_id',$data->id)->setField('auding_status',1);

//                }



            }else{

                $find = Db::name('shop_spec_attr_auding_status')->where([

                    'type' => 1,

                    'spec_id' => $param['id'],

                    'auding_status' => 2,

                    'role_id' => $role_id

                ])->find(); //当前会员



                if(!empty($find)) fail('本级别已经审核过');

                Db::name('shop_spec_attr_auding_status')->insert([

                    'auding_text' => $auding_text,

                    'count' => $param['count'],

                    'bit' => $param['bit'],

                    'type' => 1,

                    'spec_id' => $param['id'],

                    'auding_status' => 2,

                    'auding_id' => $manage_id,

                    'role_id' => $role_id,

                    'create_time' => date('Y-m-d H:i:s',time())



                ]);

                wingo('录入完毕',Url::build('chuku'));

            }

//            Db::name('shop_spec_attr_bit')->insert([

//                'spec_attr_id' => $param['id'],

//                'goods_id' => $param['goods_id'],

//                'bit' => $param['bit'],

//                'count' => $param['count'],

//                'total_bit' => $param['bit']*$param['count'],

//                'attribute' => $param['attribute'],

//                'inventory' => $param['inventory'],

//                'after_inventory' => $param['inventory']+$param['count'],

//                'create_time' => date('Y-m-d H:i:s',time())

//            ]);

//            $goods_attr = Db::name('shop_spec_attr')->where('id',$id)->setInc('inventory',$param['count']);

//            Db::name('shop_spec_attr')->where('id',$id)->update(['count' =>$param['count'],'bit' => $param['bit'],'total_bit' => $param['count']*$param['bit']]);

//            if($goods_attr){

//                $this->insert_records(1,$param['count'],$id);

//

//                win('入库成功',Url::build('chuku'));

//            }



        }

        $shenhe = Db::name('shop_spec_attr_auding_status')

            ->alias('s')

            ->join('manager m','s.auding_id = m.id')

            ->field('m.*,s.*')

            ->where(['spec_id' => $param['id'],'type' => 1])

            ->find();

        $records = Db::name('shop_spec_attr_auding_status')

            ->alias('s')

            ->join('manager m','s.auding_id = m.id','left')

            ->field('m.*,s.*')

            ->where(['spec_id' => $param['id'],'type' => 1])

            ->select()->toArray();

        foreach ($records as $k => &$v){

            $v['level'] = '等待审核';

            if($v['role_id'] == 11){

                $v['level'] = '一级审核';

            }

            if($v['role_id'] == 12){

                $v['level'] = '二级审核';

            }

            if($v['role_id'] == 13){

                $v['level'] = '三级审核';

            }





        }



        return view('',['item' => $shenhe,'records' => $records]);

    }



    /**

     * @return array|mixed|\think\response\View

     * 门店出库到门店列表

     */

    public function shop_to_shop()

    {

        $param = Request::instance()->param();

        $where = [];

        $whereTitle = [];



        if(!empty($param['shop_id'])) $where['shop_id'] = ['eq',Request::instance()->param('shop_id')];

        if(!empty($param['title'])) $whereTitle['sg.title'] = ['like','%'.$param['title'].'%'];

        if(\session('auding_status') == 2){



        }else{

            $role_id = $role_id = session('role_id');

            if($role_id != 3){

                $where['shop_id'] = ['eq',\session('shop_id')];

            }



        }





        $tongji = [];

        $data = (new \app\console\model\ShopGoods())

            ->alias('sg')

            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id')

            ->where($where)

            ->where($whereTitle)

            ->where('ssa.shop_id','gt',0)

            ->field('sg.*,ssa.shop_id')

            ->order('sg.id desc')

            ->group('ssa.goods_id')

            ->paginate(10, false, ['query' => $param])->each(function ($item, $key)  use ($where){

                $list = Db::name('shop_spec_attr ssa')

                    ->join('shop s','ssa.shop_id = s.id')

                    ->where('ssa.goods_id', $item->id)

                    ->where($where)

                    ->field('ssa.*,s.shop_title')

                    ->where('ssa.shop_id','gt',0)

                    ->select()->toArray();



                foreach ($list as $k => &$v){

                    $str = '';

                    $goods_sum = Db::name('order')

                        ->alias('o')

                        ->join('order_goods og','o.id=og.order_id')

                        ->where('o.status','in','2,3,4,6,5')

                        ->where('og.goods_id',$v['goods_id'])

                        ->where('og.shop_id',$v['shop_id'])



                        ->where('og.attribute',$v['attribute'])

                        ->sum('number');

                    $order_id = Db::name('order')

                        ->alias('o')

                        ->join('order_goods og','o.id=og.order_id')

                        ->where('o.status','in','2,3,4,6,5')

                        ->where('og.goods_id',$v['goods_id'])



                        ->where('og.shop_id',$v['shop_id'])

                        ->where('og.attribute',$v['attribute'])

                        ->value('o.id');

                 //  dump($order_id);

                    $goods_sum_price = Db::name('order')

                        ->alias('o')

                        ->join('order_goods og','o.id=og.order_id')

                        ->where('o.status','in','2,3,4,6,5')

                        ->where('og.goods_id',$v['goods_id'])

                        ->where('og.shop_id',$v['shop_id'])

                         ->where('og.attribute',$v['attribute'])

                        ->value('og.price');

                    $goods_sum2 = Db::name('order')

                        ->alias('o')

                        ->join('order_goods og','o.id=og.order_id')

                        ->where('o.status','in','2,3,4,6,5')

                        ->where('og.goods_id',$v['goods_id'])

                        ->where('og.shop_id',$v['shop_id'])

                        ->where('og.attribute',$v['attribute'])

                        ->column('order_id');

                    //'-'.implode(',',$goods_sum2

                    $v['has_buy_sum'] = $goods_sum;

                    $v['has_buy_price'] = $goods_sum_price;

                    $v['cbj'] =  Db::name('shop_spec_attr')->where('goods_id',$v['goods_id'])->where('attribute',$v['attribute'])->where('shop_id',0)->value('bit');//总库的成本价

                    $v['zly'] = bcmul(bcsub($goods_sum_price,$v['cbj'],2),$goods_sum,2);

                    $v['zsl'] = $goods_sum+$v['inventory'];

                    $records = Db::name('shop_spec_attr_auding_status')

                        ->alias('s')

                        ->join('manager m','s.auding_id = m.id','left')

                        ->where(['spec_id' => $v['id'],'type' => 3])

                        ->column('auding_text');

                    $records2 = Db::name('shop_spec_attr_auding_status')

                        ->alias('s')

                        ->join('manager m','s.auding_id = m.id','left')

                        ->where(['spec_id' => $v['id'],'type' => 4])

                        ->column('auding_text');

                    $v['level'] = implode(',',$records);

                    $v['level2'] = implode(',',$records2);







                }

                $item->list =$list;

            $item->count = count(Db::name('shop_spec_attr')->where($where)->where('goods_id', $item->id)->where('shop_id','gt',0)->select());

        });

        $chengben = 0;

        $shoumai = 0;

        $zongliyun = 0;

        $wwhere = [];

        if(!empty($param['shop_id'])) $wwhere['og.shop_id'] = ['eq',Request::instance()->param('shop_id')];

        $has_order_goods = Db::name('order')

            ->alias('o')

            ->join('order_goods og','o.id=og.order_id')

            ->where('o.status','in','2,3,4,6,5')

            ->where($wwhere)

            ->select();

        foreach ($has_order_goods as $v123){

            $cb = Db::name('shop_spec_attr')->where('goods_id',$v123['goods_id'])->where('shop_id',0)->where('attribute',$v123['attribute'])->value('bit');

            if($cb > 0){

                //dump($v123['goods_id'].'-'.$cb);

            }

            $chengben += ($cb*$v123['number']);

            $shoumai += $v123['number']*$v123['price'];

        }



//        $data2 = (new \app\console\model\ShopGoods())

//            ->alias('sg')

//            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id')

//            ->where($where)

//            ->where($whereTitle)

//            ->where('ssa.shop_id','gt',0)

//            ->field('sg.*,ssa.shop_id')

//            ->order('sg.id desc')

//            ->group('ssa.goods_id')

//            ->paginate(100000, false, ['query' => $param])->each(function ($item, $key)  use ($where,&$tongji,&$chengben,$shoumai,$zongliyun){

//                $list = Db::name('shop_spec_attr ssa')

//                    ->join('shop s','ssa.shop_id = s.id')

//                    ->where('ssa.goods_id', $item->id)

//                    ->where($where)

//                    ->field('ssa.*,s.shop_title')

//                    ->where('ssa.shop_id','gt',0)

//                    ->select()->toArray();

//

//                foreach ($list as $k => &$v){

//                    $str = '';

//                    $goods_sum = Db::name('order')

//                        ->alias('o')

//                        ->join('order_goods og','o.id=og.order_id')

//                        ->where('o.status','in','2,3,4,6,5')

//                        ->where('og.goods_id',$v['goods_id'])

//                        ->where('og.shop_id',$v['shop_id'])

//                        ->where('og.attribute',$v['attribute'])

//                        ->sum('number');

//                    $goods_sum_price = Db::name('order')

//                        ->alias('o')

//                        ->join('order_goods og','o.id=og.order_id')

//                        ->where('o.status','in','2,3,4,6,5')

//                        ->where('og.goods_id',$v['goods_id'])

//                        ->where('og.shop_id',$v['shop_id'])

//                        ->where('og.attribute',$v['attribute'])

//                        ->value('og.price');

//                    $goods_sum2 = Db::name('order')

//                        ->alias('o')

//                        ->join('order_goods og','o.id=og.order_id')

//                        ->where('o.status','in','2,3,4,6,5')

//                        ->where('og.goods_id',$v['goods_id'])

//                        ->where('og.shop_id',$v['shop_id'])

//                        ->where('og.attribute',$v['attribute'])

//                        ->column('order_id');

//                    //'-'.implode(',',$goods_sum2

//                    $v['has_buy_sum'] = $goods_sum;

//                    $v['has_buy_price'] = $goods_sum_price;

//                    $v['zly'] = bcmul(bcsub($goods_sum_price,$v['cbj'],2),$goods_sum,2);

//                    $v['zsl'] = $goods_sum+$v['inventory'];

//                    $records = Db::name('shop_spec_attr_auding_status')

//                        ->alias('s')

//                        ->join('manager m','s.auding_id = m.id','left')

//                        ->where(['spec_id' => $v['id'],'type' => 3])

//                        ->column('auding_text');

//                    $records2 = Db::name('shop_spec_attr_auding_status')

//                        ->alias('s')

//                        ->join('manager m','s.auding_id = m.id','left')

//                        ->where(['spec_id' => $v['id'],'type' => 4])

//                        ->column('auding_text');

//                    $v['level'] = implode(',',$records);

//                    $v['level2'] = implode(',',$records2);

//                    $chengben += bcmul($v['cbj'],$v['zsl'],2);

//                    $shoumai += 1;

//

//                }

//                $item->list =$list;

//                $item->count = count(Db::name('shop_spec_attr')->where($where)->where('goods_id', $item->id)->where('shop_id','gt',0)->select());

//            });

        $shop_list = Db::name('shop')->where('auding_status',2)->where('is_delete',1)->select();



        return view('', ['data' => $data,'shop_list' => $shop_list,'chengben' => $chengben,'shoumai' => $shoumai]);

    }



    public function shop_to_shop_daochu()

    {

        $param = Request::instance()->param();

        $where = [];

        if(!empty($param['shop_id'])){

            $where['ssa.shop_id'] = ['eq',Request::instance()->param('shop_id')];

        }

        if(!empty($param['title'])) $where['sg.title'] = ['like','%'.$param['title'].'%'];

        if(\session('auding_status') == 2){

        }else{

            $where['shop_id'] = ['eq',\session('shop_id')];

        }

        $data = Db::name('shop_spec_attr ssa')

            ->where($where)

            ->join('shop_goods sg','ssa.goods_id = sg.id')

            ->join('shop s','ssa.shop_id = s.id')

            ->field('ssa.*,s.shop_title,sg.title')

            ->where('ssa.shop_id','gt',0)

            ->select();

       $this->push_hop_chuku($data);

    }

    public function push_hop_chuku($data,$name = '分店出库导出')

    {

        set_time_limit(0);

        ini_set('memory_limit', '1024M');

        error_reporting(E_ALL);

        date_default_timezone_set('Asia/Shanghai');



        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');

        $objPHPExcel = new \PHPExcel();



        /*以下是一些设置 ，什么作者  标题啊之类的*/

        $objPHPExcel->getProperties()->setCreator("管理员")

            ->setLastModifiedBy("管理员")

            ->setTitle("电话本导出")

            ->setSubject("数据EXCEL导出")

            ->setDescription("备份数据")

            ->setKeywords("excel")

            ->setCategory("result file");

        $objPHPExcel->setActiveSheetIndex(0)

            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

            ->setCellValue('A1', 'ID')

            ->setCellValue('B1', '商品名称')

            ->setCellValue('C1', '属性值')

            ->setCellValue('D1', '属性库存')

            ->setCellValue('E1', '门店名称')

        ;

        $sheet1 = ['A', 'B', 'C', 'D', 'E','F'];



        for ($x = 0; $x < count($sheet1); $x++) {

            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(

                array(

                    'font'      => array(

                        'bold' => true

                    ),

                    'alignment' => array(

                        'horizontal' =>

                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER

                    )

                )

            );

        }



        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/



        $n = 0;

        foreach ($data as $v) {



            $num = $n + 2;

            $objPHPExcel->setActiveSheetIndex(0)

                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

                ->setCellValue('A' . $num, $v['id'])

                ->setCellValue('B' . $num, $v['title'])

                ->setCellValue('C' . $num,$v['attribute'])

                ->setCellValue('D' . $num, $v['inventory'])

                ->setCellValue('E' . $num, $v['shop_title'])

            ;

            $n++;

        }



        $objPHPExcel->getActiveSheet(0)->setTitle('分店出库导出');

        $objPHPExcel->setActiveSheetIndex(0);



        ob_end_clean();

        header('Content-Type: application/vnd.ms-excel');

        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');

        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $objWriter->save('php://output');

        exit;

    }



    /**

     * @param $id

     * @return array|mixed|\think\response\View

     * 门店出库到门店

     */

    public function chuku_shop_shop($id){

        $param = Request::instance()->param();

        if(Request::instance()->isPost()){

            $param['attribute'] =  Db::name('shop_spec_attr')->where('id', $param['id'])->value('attribute');

            if($param['shop_id'] <=0){

                //fail('必须选择门店');

            }

            if($param['count'] <=0){

                fail('出库数量必须大于0');

            }



            $count = count($param['shop_id'])*$param['count'];

            if($count > $param['inventory']){

                fail('出库数量不能大于总库存');

            }

            $role_id = session('role_id');



            if($role_id == 2){

                $role_id = 11;  //如果是超级管理员或者管理员就当一级审核原来玩



            }

            $auding_text = '等待审核';

            if($role_id == 11){

                $auding_text = '一级审核';

            }

            if($role_id == 12){

                $auding_text = '二级审核';

            }

            if($role_id == 13){

                $auding_text = '三级审核';

            }

            $manage_id = session('manage_id');

            if (isset($param['auding_status'])) { //有审核状态 审核权限人 2是审核成功

                //多次审核

                if($role_id != 1) {

                    $ssaas_find = Db::name('shop_spec_attr_auding_status')->where('type', 4)->where('spec_id', $param['id'])->where('role_id', 3)->find();

                    if (empty($ssaas_find)) {

                        fail('没有录入员提交,无法审核');

                    }

                }

                if($role_id == 12){

                    $auding_status1 = Db::name('shop_spec_attr_auding_status')->where('type',4)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    if(empty($auding_status1)){

                        fail('请等一级审核完毕');

                    }

                }

                if($role_id == 13){

                    $auding_status1 = Db::name('shop_spec_attr_auding_status')->where('type',4)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    $auding_status2 = Db::name('shop_spec_attr_auding_status')->where('type',4)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    if(empty($auding_status1) || empty($auding_status2)){

                        fail('请等一二级审核完毕');

                    }

                }



                //超级管理员1 管理员2 一级审核员11 二级审核员12 三级审核员13

                $status = false;



                if($param['auding_status'] != 2){ //不是成功就是删除 重新来

                    Db::name('shop_spec_attr_auding_status')->where('spec_id',$param['id'])->delete(); //全部删除重新审核

                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',$param['reason']);

                    fail('您不同意审核,审核重新开始');

                }else{

                    //成功

                    $find = Db::name('shop_spec_attr_auding_status')->where([

                        'type' => 4,

                        'spec_id' => $param['id'],

                        'auding_status' => $param['auding_status'],

                        'role_id' => $role_id

                    ])->find(); //当前会员



                    if(!empty($find)) fail('本级别已经审核过');

                    $select = Db::name('shop_spec_attr_auding_status')->where([

                        'type' => 4,

                        'spec_id' => $param['id'],

                    ])->select(); //统计数量

                    if($role_id == 1){

                        $select = ['1','2',3];

                    }

                    if(count($select) == 3){ //如果已经有2条同意了 那就是正常添加了

                        Db::name('shop_spec_attr_auding_status')->where([

                            'type' => 4,

                            'spec_id' => $param['id'],

                        ])->delete(); //删除统计记录

                        foreach ($param['shop_id'] as $k => $v){

                            $goods_attr = Db::name('shop_spec_attr')->where('goods_id',$param['goods_id'])->where('shop_id',$v)->where('attribute',$param['attribute'])->find();

                            if($goods_attr){

                                Db::name('shop_spec_attr')->where('goods_id',$param['goods_id'])->where('shop_id',$v)->where('attribute',$param['attribute'])->setInc('inventory',$param['count']);



                            }else{

                                Db::name('shop_spec_attr')->insert([

                                    'goods_id' => $param['goods_id'],

                                    'shop_id' => $v,

                                    'attribute' => $param['attribute'],

                                    'inventory' => $param['count']

                                ]);



                            }

                            if($count == $param['inventory']){ //当前门店所有库存全部清空 那就删除本条数据了

                                Db::name('shop_spec_attr')->where('id',$id)->delete();

                            }else{

                                Db::name('shop_spec_attr')->where('id',$id)->setDec('inventory',$param['count']);

                            }



                            $this->insert_records(4,$param['count'],$id,$v);

                        }

                        wingo('出库成功',Url::build('shop_to_shop'));

                    }

                    Db::name('shop_spec_attr_auding_status')->insert([

                        'auding_text' => $auding_text,

                        'shop_str' => implode(',',$param['shop_id']),

                        'count' => $param['count'],

                        'bit' => 0,

                        'type' => 4,

                        'spec_id' => $param['id'],

                        'auding_status' => $param['auding_status'],

                        'auding_id' => $manage_id,

                        'role_id' => $role_id,

                        'create_time' => date('Y-m-d H:i:s',time())



                    ]);





                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',''); //成功 就没有失败原因 清空

                    wingo('审核完毕',Url::build('shop_to_shop'));

                }



            }else{

                $find = Db::name('shop_spec_attr_auding_status')->where([

                    'type' => 4,

                    'spec_id' => $param['id'],

                    'auding_status' => 2,

                    'role_id' => $role_id

                ])->find(); //当前会员



                if(!empty($find)) fail('本级别已经审核过');

                Db::name('shop_spec_attr_auding_status')->insert([

                    'auding_text' => $auding_text,

                    'shop_str' => implode(',',$param['shop_id']),

                    'count' => $param['count'],

                    'bit' => 0,

                    'type' => 4,

                    'spec_id' => $param['id'],

                    'auding_status' => 2,

                    'auding_id' => $manage_id,

                    'role_id' => $role_id,

                    'create_time' => date('Y-m-d H:i:s',time())



                ]);

                wingo('录入完毕',Url::build('shop_to_shop'));

            }





        }



        $shop_list = Db::name('shop')->where('is_delete',1)->where('auding_status',2)->select();

        $shenhe = Db::name('shop_spec_attr_auding_status')

            ->alias('s')

            ->field('m.*,s.*')

            ->join('manager m','s.auding_id = m.id')

            ->where(['spec_id' => $param['id'],'type' => 4])

            ->find();

        $records = Db::name('shop_spec_attr_auding_status')

            ->alias('s')

            ->field('m.*,s.*')

            ->join('manager m','s.auding_id = m.id','left')

            ->where(['spec_id' => $param['id'],'type' => 4])

            ->select()->toArray();

        foreach ($records as $k => &$v){

            $v['level'] = '等待审核';

            if($v['role_id'] == 11){

                $v['level'] = '一级审核';

            }

            if($v['role_id'] == 12){

                $v['level'] = '二级审核';

            }

            if($v['role_id'] == 13){

                $v['level'] = '三级审核';

            }

        }

        return view('',['shop_list' => $shop_list,'item' => $shenhe,'records' => $records]);

    }



    /**

     * @param $id

     * @return array|mixed|\think\response\View

     * 门店出库总库

     */

    public function chuku_shop_adminer($id){

        $param = Request::instance()->param();

        if(Request::instance()->isPost()){

            $param['attribute'] =  Db::name('shop_spec_attr')->where('id', $param['id'])->value('attribute');

            if($param['count'] <=0){

                fail('出库数量必须大于0');

            }



            $count = $param['count'];

            if($count > $param['inventory']){

                fail('出库数量不能大于总库存');

            }

            $role_id = session('role_id');



            if($role_id == 2){

                $role_id = 11;  //如果是超级管理员或者管理员就当一级审核原来玩



            }

            $auding_text = '等待审核';

            if($role_id == 11){

                $auding_text = '一级审核';

            }

            if($role_id == 12){

                $auding_text = '二级审核';

            }

            if($role_id == 13){

                $auding_text = '三级审核';

            }

            $manage_id = session('manage_id');

            if (isset($param['auding_status'])) { //有审核状态 审核权限人 2是审核成功

                //多次审核

                if($role_id != 1) {

                    $ssaas_find = Db::name('shop_spec_attr_auding_status')->where('type', 3)->where('spec_id', $param['id'])->where('role_id', 3)->find();

                    if (empty($ssaas_find)) {

                        fail('没有录入员提交,无法审核');

                    }

                }

                if($role_id == 12){

                    $auding_status1 = Db::name('shop_spec_attr_auding_status')->where('type',3)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    if(empty($auding_status1)){

                        fail('请等一级审核完毕');

                    }

                }

                if($role_id == 13){

                    $auding_status1 = Db::name('shop_spec_attr_auding_status')->where('type',3)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    $auding_status2 = Db::name('shop_spec_attr_auding_status')->where('type',3)->where('spec_id',$param['id'])->where('role_id',11)->find();

                    if(empty($auding_status1) || empty($auding_status2)){

                        fail('请等一二级审核完毕');

                    }

                }

                //超级管理员1 管理员2 一级审核员11 二级审核员12 三级审核员13

                $status = false;



                if($param['auding_status'] != 2){ //不是成功就是删除 重新来

                    Db::name('shop_spec_attr_auding_status')->where('spec_id',$param['id'])->delete(); //全部删除重新审核

                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',$param['reason']);

                    fail('您不同意审核,审核重新开始');

                }else{

                    //成功

                    $find = Db::name('shop_spec_attr_auding_status')->where([

                        'type' => 3,

                        'spec_id' => $param['id'],

                        'auding_status' => $param['auding_status'],

                        'role_id' => $role_id

                    ])->find(); //当前会员



                    if(!empty($find)) fail('本级别已经审核过');

                    $select = Db::name('shop_spec_attr_auding_status')->where([

                        'type' => 3,

                        'spec_id' => $param['id'],

                    ])->select(); //统计数量

                    if($role_id == 1){

                        $select = ['1','2',3];

                    }

                    if(count($select) == 3){ //如果已经有2条同意了 那就是正常添加了

                        Db::name('shop_spec_attr_auding_status')->where([

                            'type' => 3,

                            'spec_id' => $param['id'],

                        ])->delete(); //删除统计记录

                        //

                        $goods_attr = Db::name('shop_spec_attr')->where('goods_id',$param['goods_id'])->where('shop_id',0)->where('attribute',$param['attribute'])->find();

                        if($goods_attr){ //正常来说 总库肯定是存在的

                            Db::name('shop_spec_attr')->where('goods_id',$param['goods_id'])->where('shop_id',0)->where('attribute',$param['attribute'])->setInc('inventory',$param['count']);



                        }else{

                            fail('总库当前属性不存在');

                        }

                        if($count == $param['inventory']){ //当前门店所有库存全部清空 那就删除本条数据了

                            Db::name('shop_spec_attr')->where('id',$id)->delete();

                        }else{

                            Db::name('shop_spec_attr')->where('id',$id)->setDec('inventory',$param['count']);

                        }

                        $this->insert_records(3,$param['count'],$id);

                        wingo('出库成功',Url::build('shop_to_shop'));

                        //

                    }

                    Db::name('shop_spec_attr_auding_status')->insert([

                        'auding_text' => $auding_text,

                        'count' => $param['count'],

                        'bit' => 0,

                        'type' => 3,

                        'spec_id' => $param['id'],

                        'auding_status' => $param['auding_status'],

                        'auding_id' => $manage_id,

                        'role_id' => $role_id,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);



                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',''); //成功 就没有失败原因 清空

                    wingo('审核完毕',Url::build('shop_to_shop'));

                }





            }else{

                $find = Db::name('shop_spec_attr_auding_status')->where([

                    'type' => 3,

                    'spec_id' => $param['id'],

                    'auding_status' => 2,

                    'role_id' => $role_id

                ])->find(); //当前会员

                if(!empty($find)) fail('本级别已经审核过');

                Db::name('shop_spec_attr_auding_status')->insert([

                    'auding_text' => $auding_text,

                    'count' => $param['count'],

                    'bit' => 0,

                    'type' => 3,

                    'spec_id' => $param['id'],

                    'auding_status' => 2,

                    'auding_id' => $manage_id,

                    'role_id' => $role_id,

                    'create_time' => date('Y-m-d H:i:s',time())

                ]);

                wingo('录入完毕',Url::build('shop_to_shop'));

            }



        }



        $shop_list = Db::name('shop')->where('is_delete',1)->where('auding_status',2)->select();

        $shenhe = Db::name('shop_spec_attr_auding_status')

            ->alias('s')

            ->field('m.*,s.*')

            ->join('manager m','s.auding_id = m.id')

            ->where(['spec_id' => $param['id'],'type' => 3])

            ->find();

        $records = Db::name('shop_spec_attr_auding_status')

            ->alias('s')

            ->field('m.*,s.*')

            ->join('manager m','s.auding_id = m.id','left')

            ->where(['spec_id' => $param['id'],'type' => 3])

            ->select()->toArray();

        foreach ($records as $k => &$v){

            $v['level'] = '等待审核';

            if($v['role_id'] == 11){

                $v['level'] = '一级审核';

            }

            if($v['role_id'] == 12){

                $v['level'] = '二级审核';

            }

            if($v['role_id'] == 13){

                $v['level'] = '三级审核';

            }





        }



        return view('',['shop_list' => $shop_list,'item' => $shenhe,'records' => $records]);

    }



    /**管理员修改出入库

     * @param $id

     *

     */

    public function goods_adminer_update($id)

    {

        $info = Db::name('shop_spec_attr')->where('id', $id)->find();

        if (Request::instance()->isPost()) {

            $inventory = Request::instance()->post('inventory');

            $cbj = Request::instance()->post('bit');

            Db::name('shop_spec_attr')->where('id', $id)->update(['inventory' => $inventory,'bit' => $cbj]);

            wingo('修改成功', Url::build('chuku'));

        }

        return view('', ['info' => $info]);

    }



    /**

     * @param $id

     * @return array|mixed|\think\response\View

     * 管理员修改门店出入库

     */

    public function goods_adminer_update2($id)

    {

        $info = Db::name('shop_spec_attr')->where('id', $id)->find();

        if (Request::instance()->isPost()) {

            $inventory = Request::instance()->post('inventory');

            $cbj = Request::instance()->post('cbj');

            Db::name('shop_spec_attr')->where('id', $id)->update(['inventory' => $inventory,'cbj' => $cbj]);

            wingo('修改成功', Url::build('shop_to_shop'));

        }

        return view('shop_goods_goods_adminer_update2', ['info' => $info]);

    }





    public function insert_records($type,$count,$spec_id = 0,$shop_id = 0){

        Db::name('inevntory_records')->insert(['type' => $type,'count' => $count,'spec_id' => $spec_id,'shop_id' => $shop_id,'create_time' => date('Y-m-d H:i:s',time())]);

    }



    public function records()

    {

        $param = Request::instance()->param();

        $where = [];

        if (!empty($param['type'])) $where['ir.type'] = ['eq', $param['type']];

        if (!empty($param['title'])) $where['sg.title|ir.count|ssa.attribute'] = ['like', '%'.$param['title'].'%'];

        if (!empty($param['shop_id'])) $where['s.id'] = ['eq', $param['shop_id']];

        $data = Db::name('inevntory_records ir')

            ->join('shop_spec_attr ssa', 'ir.spec_id = ssa.id', 'left')

            ->join('shop_goods sg','ssa.goods_id = sg.id')

            ->join('shop s', 'ir.shop_id = s.id', 'left')

            ->field('ir.*,s.shop_title,ssa.shop_id shop_id_0_or_1,ssa.goods_id,ssa.attribute,sg.title')

            ->order('ir.id', 'desc')

            ->where($where)

            ->paginate(10, false, ['query' => $param]);

        return view('', ['data' => $data]);

    }

    public function daochu(){

        $where = [];

        $param = Request::instance()->param();

        if (!empty($param['type'])) $where['ir.type'] = ['eq', $param['type']];

        if (!empty($param['title'])) $where['sg.title|ir.count|ssa.attribute'] = ['like', '%'.$param['title'].'%'];

        if (!empty($param['shop_id'])) $where['s.id'] = ['eq', $param['shop_id']];

        $data =Db::name('inevntory_records ir')

            ->join('shop_spec_attr ssa','ir.spec_id = ssa.id','left')

            ->join('shop_goods sg','ssa.goods_id = sg.id')

            ->join('shop s','ir.shop_id = s.id','left')

            ->field('ir.*,s.shop_title,ssa.shop_id shop_id_0_or_1,ssa.goods_id,ssa.attribute,sg.title')

            ->order('ir.id','desc')

            ->where($where)

            ->paginate(10000,false,['query' => $param])->toArray();

        if(!empty($data)){

            foreach ($data['data'] as $k => &$v){

                if($v['type'] == 1) $v['type'] = '总库入库';

                if($v['type'] == 2) $v['type'] = '总库出库门店';

                if($v['type'] == 3) $v['type'] = '门店出库总库';

                if($v['type'] == 4) $v['type'] = '门店出库门店';

            }

        }

        $this->push_coupon($data['data'],'出入库记录导出');



    }

    public function push_coupon($data,$name = 'Excel')

    {

        set_time_limit(0);

        ini_set('memory_limit', '1024M');

        error_reporting(E_ALL);

        date_default_timezone_set('Asia/Shanghai');



        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');

        $objPHPExcel = new \PHPExcel();



        /*以下是一些设置 ，什么作者  标题啊之类的*/

        $objPHPExcel->getProperties()->setCreator("管理员")

            ->setLastModifiedBy("管理员")

            ->setTitle("电话本导出")

            ->setSubject("数据EXCEL导出")

            ->setDescription("备份数据")

            ->setKeywords("excel")

            ->setCategory("result file");

        $objPHPExcel->setActiveSheetIndex(0)

            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

            ->setCellValue('A1', '出入库类型')

            ->setCellValue('B1', '出入库数量')

            ->setCellValue('C1', '出入库规格')

            ->setCellValue('D1', '出入库到门店');

        $sheet1 = ['A', 'B', 'C', 'D', 'I'];



        for ($x = 0; $x < count($sheet1); $x++) {

            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(

                array(

                    'font'      => array(

                        'bold' => true

                    ),

                    'alignment' => array(

                        'horizontal' =>

                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER

                    )

                )

            );

        }



        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/



        $n = 0;

        foreach ($data as $v) {



            $num = $n + 2;

            $objPHPExcel->setActiveSheetIndex(0)

                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

                ->setCellValue('A' . $num, $v['type'])

                ->setCellValue('B' . $num, $v['count'])

                ->setCellValue('C' . $num, $v['goods_id'].'/'.$v['title'].'/'.$v['attribute'])

                ->setCellValue('D' . $num, $v['shop_title']);

            $n++;

        }



        $objPHPExcel->getActiveSheet(0)->setTitle('出入库记录导出');

        $objPHPExcel->setActiveSheetIndex(0);



        ob_end_clean();

        header('Content-Type: application/vnd.ms-excel');

        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');

        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $objWriter->save('php://output');

        exit;

    }



    /*

     * 仓库中的商品

     */

    public function warehouse()

    {

        // 获取参数

        $inquire = Request::instance()->param();



        // 搜索条件

        $condition['state'] = ['eq', '2'];

        $condition['member_id'] = ['eq', Session::get('shop_id')];

        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];

        if (!empty($inquire['shop_class_id'])) $condition['parenTid'] = ['eq', $inquire['shop_class_id']];



        // 读取店铺分类店铺商品

        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select();

        // 读取店铺商品

        $data = ShopGoodsModel::where($condition)->field('id,price,parenTid,sort,sale_number,title,create_time,state')->order(['id' => 'desc'])->paginate(10, false, ['query' => $inquire]);



        return $this->fetch('warehouse', [

            'mate_title'   => '仓库中的商品',

            'data'         => $data,

            'classify'     => ClassifyAlias::dimension(Cache::get('goodsType')),

            'shopClassify' => $shopClassify

        ]);

    }



    /*

     * 违规的商品

     */

    public function violation()

    {

        // 获取参数

        $inquire = Request::instance()->param();



        // 搜索条件

        $condition['status'] = ['eq', '3'];

        $condition['member_id'] = ['eq', Session::get('shop_id')];

        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];

        if (!empty($inquire['shop_class_id'])) $condition['parenTid'] = ['eq', $inquire['shop_class_id']];



        // 读取店铺分类店铺商品

        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select();

        // 读取店铺商品

        $data = ShopGoodsModel::where($condition)->field('id,price,parenTid,sort,sale_number,title,create_time,collect,cause')->order(['id' => 'desc'])->paginate(10, false, ['query' => $inquire]);



        return $this->fetch('violation', [

            'mate_title'   => '违规中的商品',

            'data'         => $data,

            'classify'     => ClassifyAlias::dimension(Cache::get('goodsType')),

            'shopClassify' => $shopClassify

        ]);

    }



    /*

     * 店铺分类联动选择

     */

    public function linkage()

    {

        $parenTid = Request::instance()->param('parenTid');

        if (!empty($parenTid))

            return GoodsTypeModel::where(['parenTid' => $parenTid])->field('id,count,title')->order(['id' => 'asc'])->select();

        else

            return false;

    }





    /*

     * 店铺商品添加

     */

    public function create()

    {



        if (Request::instance()->isPost()) {



            $data = Request::instance()->param();



            // 验证

            $validate = Loader::validate('ShopGoods','validate',false,'client');

            if (!$validate->scene('create')->check($data)) fail($validate->getError());



            $model = new ShopGoodsModel();



            // 提交数据

            $dispose = $model->allowField(true)->save($data);



            if (!empty($data['nameAttr'])) {

                // 一对多添加数组

                $flagArr = [];



                for ($i = 0; $i < count($data['nameAttr']); $i++) {

                    $flagArr[$i]['goods_id'] = $model->id;

                    $flagArr[$i]['flag_name'] = $data['nameAttr'][$i];

                    $flagArr[$i]['flag_value'] = $data['valueAttr'][$i];

                }



                $model->flagAttr()->saveAll($flagArr);

            }





            if ($dispose) {

                win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));

            }



            fail('操作失败');



        }



        //获取分类id

        $goods_id = Request::instance()->param('goods_id');



        if (empty($goods_id)) throw new Exception('goodsId not empty');





        // 读取店铺分类店铺商品

        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count,sort')->select()->toArray();



        // 读取类别品牌

        $brand = BrandModel::all();



        // 读取店铺规格

        //$attr = ShopGoodsSpecModel::where('goods_type_id' ,['like', '%,' . $goods_id . ',%'])->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select();

        $attr = ShopGoodsSpecModel::where('goods_type_id' ,'like', '%,' . $goods_id . ',%')->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select();

//        foreach ($attr as &$value) {

//            // 获取attr参数

//            $value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id,'or'])->select();

//        }



        foreach ($attr as &$value) {

            // 获取attr参数

            ////$value['attribute'] = ShopGoodsAttrModel::where('spec_id','eq',$value['id'])->where('goods_type_id',['eq',$goods_id],['eq',0],'or')->select();

            $value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id])->select();

            //$value['attribute'] = ShopGoodsAttrModel::where('spec_id',['eq',$value['id']], 'goods_type_id',['eq',$goods_id],'or')->select();

        }

        $shop = Db::name('shop')->where('auding_status',2)->where('is_delete',1)->select();



        return $this->fetch('create', [

            "mate_title"   => '店铺商品添加',

            'shopClassify' => ClassifyAlias::dimension($shopClassify),

            'brand'        => $brand,

            'attr'         => $attr,

            'shop' => $shop

        ]);



    }





    /*

     * 库存中的商品编辑

     */

    public function compiler($id)

    {

        if (Request::instance()->isPost()) {



            $data = Request::instance()->param();



            // 验证

            $validate = Loader::validate('ShopGoods');

            if (!$validate->scene('create')->check($data)) fail($validate->getError());



            $model = new ShopGoodsModel();



            // 提交数据

            $dispose = $model->allowField(true)->save($data, ['id' => $id]);



            if (!empty($data['nameAttr'])) {

                // 一对多添加数组

                $flagArr = [];



                for ($i = 0; $i < count($data['nameAttr']); $i++) {



                    if (!empty($data['flag_id'][$i])) {

                        $flagArr[$i]['id'] = $data['flag_id'][$i];

                    }

                    $flagArr[$i]['goods_id'] = $id;

                    $flagArr[$i]['flag_name'] = $data['nameAttr'][$i];

                    $flagArr[$i]['flag_value'] = $data['valueAttr'][$i];

                }



                (new ShopGoodsFlagModel())->saveAll($flagArr);

            }



            if ($dispose) {

                win('操作成功', Url::build('ShopGoods/warehouse', ['orderId' => 'sort']));

            }



            fail('操作失败');



        }



        //获取分类id

        $goods_id = Request::instance()->param('goods_id');



        // 读取数据

        $item = ShopGoodsModel::get($id);



        $item['spec_attr'] = ShopSpecAttr::where(['goods_id' => $id])->select();



        if (empty($goods_id)) $goods_id = $item['goods_id'];;





        // 读取店铺属性

        $attr = ShopGoodsSpecModel::where(['member_id' => Session::get('shop_id'), 'goods_type_id' => ['like', '%,' . $goods_id . ',%']])->where('auding_status',2)->where('is_delete',1)->select();



        foreach ($attr as &$value) {

            // 获取attr参数

            //$value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id])->select();

            $value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id])->select();

        }





        // 读取店铺分类店铺商品

        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select()->toArray();



        // 读取类别品牌

        $brand = BrandModel::all();



        // 读取商品规格

        $flag_list = ShopGoodsFlagModel::all(['goods_id' => $id]);



        return $this->fetch('create', [

            "mate_title"   => '店铺商品编辑',

            'shopClassify' => ClassifyAlias::dimension($shopClassify),

            'brand'        => $brand,

            'attr'         => $attr,

            'item'         => $item,

            'flag_list'    => $flag_list



        ]);

    }









    /*

     * 店铺商品删除

     */

    public function destroy()

    {



        $id = Request::instance()->param('id');

        //$find = Db::name('shop_spec_attr')->where(['goods_id' => $id,'shop_id' =>0])->find();

        $find = Db::name('shop_spec_attr')->where(['goods_id' => $id,'shop_id' =>['gt',0],'inventory' => ['gt',0]])->find();



        if(!empty($find)){

           // Db::name('shop_spec_attr')->where(['goods_id' => $id,'shop_id' =>0])->delete();

            fail('已出库商品不支持删除');

        }



        // 启动事务

        Db::startTrans();

        try {



            // 删除商品

            Db::name('shop_goods')->where(['id' => $id])->delete();

            // 删除属性关联表

            Db::name('shop_spec_attr')->where(['goods_id' => $id])->delete();

            // 提交事务

            Db::commit();



            win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));



        } catch (\Exception $e) {



            // 回滚事务

            Db::rollback();



            win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));

        }



        // if (ShopGoodsModel::destroy($id)) {

        //     win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));

        // }

        //

        // fail('操作失败');



    }



    /*

     * 店铺商品编辑

     */

    public function update($id)

    {

        $data = Request::instance()->param();

        if (Request::instance()->isPost()) {

            $spec = Request::instance()->param('sp_val/a');

            $goods_attr = unserialize(Db::name('shop_goods')->where('id',$id)->value('goods_attr'));

            if(!empty($spec) && !empty($goods_attr)){

                if(count($spec) != count($goods_attr)){

                    fail('当前属性类和原属性类不统一');

                }

            }

            if(!Request::instance()->param('sp_val/a')){

               //fail('请添加商品规格');

            }

            // 验证

            $validate = Loader::validate('ShopGoods','validate',false,'client');

            if (!$validate->scene('create')->check($data)) fail($validate->getError());



            $model = new ShopGoodsModel();

            unset($data['sp_val']);



            // 提交数据

            $dispose = $model->allowField(true)->save($data, ['id' => $id]);



            if (!empty($data['nameAttr'])) {

                // 一对多添加数组

                $flagArr = [];



                for ($i = 0; $i < count($data['nameAttr']); $i++) {



                    if (!empty($data['flag_id'][$i])) {

                        $flagArr[$i]['id'] = $data['flag_id'][$i];

                    }

                    $flagArr[$i]['goods_id'] = $id;

                    $flagArr[$i]['flag_name'] = $data['nameAttr'][$i];

                    $flagArr[$i]['flag_value'] = $data['valueAttr'][$i];

                }



                (new ShopGoodsFlagModel())->saveAll($flagArr);

            }



            if ($dispose !== false) {

                wingo('操作成功',Url::build('ShopGoods/index', ['orderId' => 'sort'])."?page=".input('page',1));

            }



            fail('操作失败');



        }



        //获取分类id

        $goods_id = Request::instance()->param('goods_id');



        // 读取数据

        $item = ShopGoodsModel::get($id);



        $item['spec_attr'] = ShopSpecAttr::where(['goods_id' => $id])->where('shop_id',0)->where('attribute','neq','无')->select();



        if (empty($goods_id)) $goods_id = $item['goods_id'];

        $sql_goods_attr = unserialize(Db::name('shop_goods')->where('id',$id)->value('goods_attr'));

        // 读取店铺属性

        $in_str = [];

        if(!empty($sql_goods_attr)){

            foreach ($sql_goods_attr as $kkk => $vvv){

                $in_str[] = $kkk;

            }

        }



        //$attr = ShopGoodsSpecModel::where('goods_type_id' ,['like', '%,' . $goods_id . ',%'],['eq',''],'or')->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select();

        $attr = ShopGoodsSpecModel::where('goods_type_id' ,'like', '%,' . $goods_id . ',%')->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select();

        foreach ($attr as $kv => &$value) {

            // 获取attr参数

                if(in_array($value['title'],$in_str)){

                    $value['attribute'] = ShopGoodsAttrModel::where('spec_id','eq',$value['id'])->where('goods_type_id',['eq',$goods_id],['eq',0],'or')->select();

                }else{

                    unset($attr[$kv]);

                }



                }







            //$value['attribute'] = ShopGoodsAttrModel::where('spec_id',['eq',$value['id']], 'goods_type_id',['eq',''])->select();







//        array(1) {

//        ["颜色"] => array(6) {

//            [49] => string(3) "黑"

//            [50] => string(3) "棕"

//            [51] => string(3) "粉"

//            [52] => string(3) "红"

//            [53] => string(3) "黄"

//            [54] => string(3) "蓝"

//  }

//}

        // 读取店铺分类店铺商品

        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count,sort')->select()->toArray();





        // 读取商品规格

        $flag_list = ShopGoodsFlagModel::all(['goods_id' => $id]);



//        $attr[1] = [

//            ['id' => 1,'goods_type_id' => ',2901,','member_id' => 0,'title' => '门店1','attribute' => [

//                'id' => '2240','goods_type_id' => 2901,'spec_id' => 1, 'title' => '原形'

//                ]

//            ]

//        ];

        //halt($attr->toArray());

        $shop = Db::name('shop')->where('auding_status',2)->where('is_delete',1)->select();

        $r = '';

        $d_shop = Db::name('shop_spec_attr')->field('DISTINCT shop_id')->where('goods_id',$id)->select()->toArray();

        $instr = [];

        if($d_shop){

            foreach ($d_shop as $k => $v){

                $instr[] = $v['shop_id'];

            }

            $r = implode(",",$instr);



        }

        $inventory_sum = Db::name('shop_spec_attr')->where('goods_id',$id)->sum('inventory');

        return $this->fetch('create', [

            "mate_title"   => '店铺商品编辑',

            'shopClassify' => ClassifyAlias::dimension($shopClassify),

            'attr'         => $attr,

            'd_shop' => $r,

            'item'         => $item,

            'shop' => $shop,

            'inventory_sum' => $inventory_sum,

            'flag_list'    => $flag_list



        ]);

    }



    public function inv(){

        $param = Request::instance()->param('shop_id');

        $goods_id = Request::instance()->param('goods_id');

        $data = Db::name('shop_spec_attr')->where('shop_id','in',$param)->where('goods_id',$goods_id)->column('inventory');

        return json_encode($data);

    }

    public function invv(){

        $param = Request::instance()->param('shop_id');

        $goods_id = Request::instance()->param('goods_id');

        $data = Db::name('shop_spec_attr')->where('shop_id','in',$param)->where('goods_id',$goods_id)->column('');

        return json_encode($data);

    }



    public function kc(){

        $shop_id = Request::instance()->param('shop_id');

        $attr = Request::instance()->param('attr');

        $goods_id = Request::instance()->param('goods_id');

        $data = Db::name('shop_spec_attr')->where('shop_id','in',$shop_id)->where('goods_id',$goods_id)->where('attribute',$attr)->value('inventory');

        return json_encode($data);

    }



    /*

     * 猜你喜欢状态改变

     */

    public function related()

    {

        $id = Request::instance()->param('id');

        $related = ShopGoodsModel::where('id', $id)->value('related') == '1' ? 2 : 1;

        if (ShopGoodsModel::where('id', $id)->update(['related' => $related])) {

            return $related;

        }

        return false;

    }



    /*

     * 店铺促销状态

     */

    public function auditing()

    {

        $id = Request::instance()->param('id');

        $recommend = ShopGoodsModel::where('id', $id)->value('recommend') == '1' ? 2 : 1;

        if (ShopGoodsModel::where('id', $id)->update(['recommend' => $recommend])) {

            return $recommend;

        }

        return false;

    }



    /*

     * 促销状态改变

     */

    public function shop_recommend()

    {

        $id = Request::instance()->param('id');

        $promotion = ShopGoodsModel::where('id', $id)->value('state') == '1' ? 2 : 1;

        if (ShopGoodsModel::where('id', $id)->update(['state' => $promotion])) {

            return $promotion;

        }

        return false;

    }



    /*

     * 上架状态改变

     */

    public function dispose_state()

    {

        $id = Request::instance()->param('id');

        $state = ShopGoodsModel::where('id', $id)->value('state') == '1' ? 2 : 1;

        if (ShopGoodsModel::where('id', $id)->update(['state' => $state])) {

            return $state;

        }

        return false;

    }



    /*

     * 上架状态改变

     */

    public function putAway()

    {

        $id = Request::instance()->param('id');

        $state = ShopGoodsModel::where('id', $id)->value('state') == '1' ? 2 : 1;

        if (ShopGoodsModel::where('id', $id)->update(['state' => $state])) {

            return $state;

        }

        return false;

    }



    /*

     * 排列顺序

     */

    public function sorting()

    {



        $id = Request::instance()->param('orderId/a');

        $sort = Request::instance()->param('sort/a');



       if($id){

           foreach ($id as $key => $value) {

               ShopGoodsModel::where('id', $value)->update(['sort' => $sort[$key]]);

           }

       }



        winfo('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));

    }

    public function goods_sale()

    {



        try {

            $id = Request::instance()->param('orderId2/a');

            $sort = Request::instance()->param('goods_sale/a');



            if ($id) {

                foreach ($id as $key => $value) {



                    $ret = ShopGoodsModel::where('id', $value)->update(['goods_sale' => $sort[$key]]);



                }

            }

            dump(1);

        } catch (\Exception $e) {

            return $e->getMessage();

        }



        winfo('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));

    }



    /**

     * @param $id删除商品属性

     */

    public function delete_spec($id){

        $ret = Db::name('shop_spec_attr')->where('id',$id)->delete();



        winfo('删除成功', Url::build('shop_to_shop'));

    }



    /**

     *

     * 门店商品提成 -服务

     */

    public function shop_ticheng($id)

    {

        $goods_id = input('id');

        $shop_list = Db::name('shop')->where('auding_status', 2)->where('is_delete', 1)->select()->toArray();

        if(!empty($shop_list)){

            foreach ($shop_list as &$v){

                $v['price'] = Db::name('goods_shop_price')->where('goods_id',$goods_id)->where('shop_id',$v['id'])->value('price');

            }

        }

        $title = Db::name('shop_goods')->where('id',$id)->value('title');

        return view('', ['shop_list' => $shop_list,'title' => $title]);

    }

    /**

     *

     * 门店商品提成

     */

    public function shop_ticheng1($id)

    {

        $goods_id = input('id');

        $shop_list = Db::name('shop')->where('auding_status', 2)->where('is_delete', 1)->select()->toArray();

        if(!empty($shop_list)){

            foreach ($shop_list as &$v){

                $v['price'] = Db::name('goods_shop_price1')->where('goods_id',$goods_id)->where('shop_id',$v['id'])->value('price');

            }

        }

        $title = Db::name('shop_goods')->where('id',$id)->value('title');

        return view('', ['shop_list' => $shop_list,'title' => $title]);

    }







    /**

     *

     */

    public function servicePriceUpdate()

    {

        $goods_id = input('goods_id');

        $param = Request::instance()->param()['input2'];



        if (!empty($param)) {

            $ret = false;

            foreach ($param as $k => $v) {

                $find = Db::name('goods_shop_price')->where('shop_id', $k)->where('goods_id', $goods_id)->find();

                if($find){ //存在就是修改

                    $ret = Db::name('goods_shop_price')->where('shop_id', $k)->where('goods_id', $goods_id)->update(['price' => $v]);

                }else{

                    $ret = Db::name('goods_shop_price')->insert([

                        'goods_id' => $goods_id,

                        'shop_id' => $k,

                        'price' => $v,

                    ]);

                }



            }

            if ($ret !== false) {

                wingo('门店服务金额设置完毕', Url::build('shop_ticheng',['id' => $goods_id]));

            }

        }

    }



    /**

     *门店商品售卖提成

     */

    public function servicePriceUpdate1()

    {

        $goods_id = input('goods_id');

        $param = Request::instance()->param()['input2'];



        if (!empty($param)) {

            $ret = false;

            foreach ($param as $k => $v) {

                $find = Db::name('goods_shop_price1')->where('shop_id', $k)->where('goods_id', $goods_id)->find();

                if($find){ //存在就是修改

                    $ret = Db::name('goods_shop_price1')->where('shop_id', $k)->where('goods_id', $goods_id)->update(['price' => $v]);

                }else{

                    $ret = Db::name('goods_shop_price1')->insert([

                        'goods_id' => $goods_id,

                        'shop_id' => $k,

                        'price' => $v,

                    ]);

                }



            }

            if ($ret !== false) {

                wingo('门店服务金额设置完毕', Url::build('shop_ticheng1',['id' => $goods_id]));

            }

        }

    }

    /*

     * 上传组图

     */



}

